import { Modal, Form, Input, Button, Space, message, Radio, Select } from 'antd'
import http from '../api/http'
import type { IDisease } from '../types/disease'
import type { FormInstance } from 'antd'
import { useEffect, useState } from 'react'

// 固定就诊科室数据（1001、1002、1003等）
const fixedDeptList = [
  { id: 1001, name: '内科' },
  { id: 1002, name: '外科' },
  { id: 1003, name: '儿科' },
  { id: 1004, name: '妇产科' },
  { id: 1005, name: '骨科' }
]

// 预警等级选项
const warnLevelOptions = [
  { id: '一级', name: '一级' },
  { id: '二级', name: '二级' },
  { id: '三级', name: '三级' }
]

// 异常类型选项
const exceptionTypeOptions = [
  { id: '系统自带', name: '系统自带' },
  { id: '自定义', name: '自定义' }
]

interface Props {
  EditModalOpen: boolean
  EditHandleCancel: () => void
  onSuccess: () => void
  editData?: any  // 兼容疾病表数据结构
}

const Edit: React.FC<Props> = ({ EditModalOpen, EditHandleCancel, onSuccess, editData }) => {
  const [form] = Form.useForm<FormInstance<any>>()  // 使用通用类型
  // 直接使用固定科室数据，无需从接口获取
  const [deptList] = useState(fixedDeptList)

  // 初始化表单数据
  useEffect(() => {
    if (editData) {
      form.setFieldsValue({
        code: editData.code,
        name: editData.name,
        deptid: editData.deptid,
        warnlevel: editData.warnlevel,
        treatperiod: editData.treatperiod,
        exceptiontype: editData.exceptiontype,
        isoccupational: editData.isoccupational,
        gender: editData.gender,
        othername: editData.othername,
        medicalinterpret: editData.medicalinterpret,
        reason: editData.reason,
        advice: editData.advice,
        remark: editData.remark
      })
    }
  }, [editData, form])

  // 提交表单
  const handleSubmit = () => {
    form.validateFields()
      .then(values => {
        if (!editData) {
          message.warning('未获取到待修改的疾病数据')
          return
        }

        // 构建疾病表提交数据
        const submitData = {
          ...values,
          id: editData.id
        }
        
        // 调用疾病表修改接口
        http.put('disease', submitData)
          .then(() => {
            message.success('修改成功')
            EditHandleCancel()
            form.resetFields()
            onSuccess()
          })
          .catch(err => {
            console.error('修改失败:', err)
            message.error('修改失败，请重试')
          })
      })
      .catch(info => {
        console.log('表单验证失败:', info)
        message.warning('请完善必填字段')
      })
  }

  return (
    <Modal
      title="修改疾病信息" 
      open={EditModalOpen}
      onCancel={EditHandleCancel}
      centered
      footer={[
        <Button key="cancel" onClick={EditHandleCancel}>
          取消
        </Button>,
        <Button key="submit" type="primary" onClick={handleSubmit}>
          确认修改
        </Button>
      ]}
      destroyOnClose={true}
      width={700}
      disabled={!editData}
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{}}
      >
        <Space style={{ width: '100%' }}>
          <Form.Item
            name="code"
            label="疾病编码"
            rules={[{ required: true, message: '请输入疾病编码' }]}
            style={{ flex: 1, marginRight: 16 }}
          >
            <Input placeholder="如：JB0001" />
          </Form.Item>

          <Form.Item
            name="name"
            label="疾病名称"
            rules={[{ required: true, message: '请输入疾病名称' }]}
            style={{ flex: 2 }}
          >
            <Input placeholder="请输入疾病全称" />
          </Form.Item>
        </Space>

        <Space style={{ width: '100%' }}>
          <Form.Item
            name="deptid"
            label="就诊科室"
            rules={[{ required: true, message: '请选择就诊科室' }]}
            style={{ flex: 1, marginRight: 16 }}
          >
            <Select placeholder="选择科室">
              {/* 使用固定科室数据渲染选项，显示ID和名称 */}
              {deptList.map(dept => (
                <Select.Option key={dept.id} value={dept.id}>
                  {dept.name}（{dept.id}）
                </Select.Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="warnlevel"
            label="预警等级"
            rules={[{ required: true, message: '请选择预警等级' }]}
            style={{ flex: 1, marginRight: 16 }}
          >
            <Radio.Group>
              {warnLevelOptions.map(level => (
                <Radio key={level.id} value={level.id}>
                  {level.name}
                </Radio>
              ))}
            </Radio.Group>
          </Form.Item>

          <Form.Item
            name="treatperiod"
            label="就医期限"
            rules={[{ required: true, message: '请输入就医期限' }]}
            style={{ flex: 1 }}
          >
            <Input placeholder="如：三个月内" />
          </Form.Item>
        </Space>

        <Space style={{ width: '100%' }}>
          <Form.Item
            name="exceptiontype"
            label="异常类型"
            rules={[{ required: true, message: '请选择异常类型' }]}
            style={{ flex: 1, marginRight: 16 }}
          >
            <Radio.Group>
              {exceptionTypeOptions.map(type => (
                <Radio key={type.id} value={type.id}>
                  {type.name}
                </Radio>
              ))}
            </Radio.Group>
          </Form.Item>

          <Form.Item
            name="isoccupational"
            label="是否职业病"
            rules={[{ required: true, message: '请选择是否职业病' }]}
            style={{ flex: 1, marginRight: 16 }}
          >
            <Radio.Group>
              <Radio value={1}>是</Radio>
              <Radio value={0}>否</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item
            name="gender"
            label="适用性别"
            rules={[{ required: true, message: '请选择适用性别' }]}
            style={{ flex: 1 }}
          >
            <Radio.Group>
              <Radio value={0}>男</Radio>
              <Radio value={1}>女</Radio>
            </Radio.Group>
          </Form.Item>
        </Space>

        <Form.Item
          name="othername"
          label="疾病别名"
        >
          <Input placeholder="请输入疾病别名（可选）" />
        </Form.Item>

        <Form.Item
          name="medicalinterpret"
          label="医学解释"
          rules={[{ required: true, message: '请输入医学解释' }]}
        >
          <Input.TextArea rows={3} placeholder="请简要描述疾病的医学定义" />
        </Form.Item>

        <Form.Item
          name="reason"
          label="常见原因"
          rules={[{ required: true, message: '请输入常见原因' }]}
        >
          <Input.TextArea rows={3} placeholder="请说明疾病的常见诱发因素" />
        </Form.Item>

        <Form.Item
          name="advice"
          label="就医建议"
          rules={[{ required: true, message: '请输入就医建议' }]}
        >
          <Input.TextArea rows={3} placeholder="请给出针对性的就医或护理建议" />
        </Form.Item>

        <Form.Item
          name="remark"
          label="备注"
        >
          <Input.TextArea rows={2} placeholder="请输入备注信息（可选）" />
        </Form.Item>
      </Form>
    </Modal>
  )
}

export { Edit }